import { Injectable, Inject, BadRequestException } from '@nestjs/common';
import { CreateFeedbackDto, SolveType } from './dto/create-feedback.dto';
import { PrismaService } from 'src/libs/prisma/prisma.service';
import { formatDate, generateSnowId } from 'src/utils';
import { RedisService } from 'src/libs/redis/redis.service';
import * as dayjs from 'dayjs';

@Injectable()
export class FeedbackService {
  @Inject(PrismaService)
  private readonly prisma: PrismaService;

  @Inject(RedisService)
  private readonly redisService: RedisService;

  async create(createFeedbackDto: CreateFeedbackDto, userId: string) {
    const key = `feedback:${userId}`;
    // 1 检查并递增计数器
    const cacheCount = await this.redisService.incr(key);
    if (cacheCount === 1) {
      // 第一次设置，需要设置过期时间
      const now = dayjs();
      const endOfDay = dayjs().endOf('day');
      const remainingSeconds = Math.floor(endOfDay.diff(now, 'millisecond') / 1000);
      await this.redisService.setWithTTL(key, remainingSeconds);
    }
    if (cacheCount > 3) {
      // 超过限制，回退计数器
      await this.redisService.decr(key);
      throw new BadRequestException('今日已反馈三次，请明天再重新反馈');
    }
    // 2 创建反馈记录
    await this.prisma.feedBack.create({ data: { ...createFeedbackDto, id: generateSnowId(), feedbackBy: userId } });
  }

  async findAll(userId: string) {
    const feedbacks = await this.prisma.feedBack.findMany({
      where: { feedbackBy: userId },
      orderBy: { createTime: 'desc' },
      select: {
        type: true,
        content: true,
        solveType: true,
        replyContent: true,
        createTime: true,
        updateTime: true,
      },
    });

    // 转换时间格式为 YYYY-MM-DD
    return feedbacks.map((feedback) => ({
      ...feedback,
      createTime: formatDate(feedback.createTime),
      updateTime: formatDate(feedback.updateTime),
    }));
  }

  solve(id: string, replyContent: string, solveType: SolveType) {
    return this.prisma.feedBack.update({
      where: { id },
      data: { solveType, replyContent },
    });
  }
}
